package com.game.arena.handler;

import com.game.center.AsyncArenaDao;
import com.game.center.entity.Arena;
import com.game.center.entity.manager.ArenaManager;
import com.game.gateway.channel.AbstractGameChannelHandlerContext;
import com.game.gateway.channel.GameChannelPromise;
import com.game.gateway.handler.AbstractGameMessageDispatchHandler;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.Optional;

public class ArenaGatewayHandler extends AbstractGameMessageDispatchHandler<ArenaManager> {
    private ArenaManager arenaManager;
    private AsyncArenaDao asyncArenaDao;
    private Logger logger = LoggerFactory.getLogger(ArenaGatewayHandler.class);

    public ArenaGatewayHandler(ApplicationContext applicationContext) {
        super(applicationContext);
        this.asyncArenaDao = applicationContext.getBean(AsyncArenaDao.class);
    }
    @Override
    protected ArenaManager getDataManager() {
        return arenaManager;
    }

    @Override
    protected Future<Boolean> updateToRedis(Promise<Boolean> promise) {
         asyncArenaDao.updateToRedis(playerId, arenaManager.getArena(),promise);
         return promise;
    }

    @Override
    protected Future<Boolean> updateToDB(Promise<Boolean> promise) {
         asyncArenaDao.updateToDB(playerId, arenaManager.getArena(), promise);
         return promise;
    }


    @Override
    protected void initData(AbstractGameChannelHandlerContext ctx, long playerId, GameChannelPromise promise) {
        // 异步加载竞技场信息
        Promise<Optional<Arena>> arenaPromise = new DefaultPromise<>(ctx.executor());
        asyncArenaDao.findArena(playerId, arenaPromise).addListener(new GenericFutureListener<Future<Optional<Arena>>>() {
            @Override
            public void operationComplete(Future<Optional<Arena>> future) throws Exception {
                if (future.isSuccess()) {
                    Optional<Arena> arOptional = future.get();
                    if (arOptional.isPresent()) {
                        arenaManager = new ArenaManager(arOptional.get());
                    } else {
                        Arena arena = new Arena();
                        arena.setPlayerId(playerId);
                        arenaManager = new ArenaManager(arena);
                    }
                    promise.setSuccess();
                } else {
                    logger.error("查询竞技场信息失败", future.cause());
                    promise.setFailure(future.cause());
                }
            }
        });

    }
}
